package cn.anecansaitin.whimsy.common.listener;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.common.register.ModItems;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.event.entity.EntityStruckByLightningEvent;

import java.util.Random;

@Mod.EventBusSubscriber(modid = Whimsy.MODID)
public class PhantasmArrowCraftingEvent {
    private static final Random random = new Random();

    @SubscribeEvent
    public static void struckByLightning(EntityStruckByLightningEvent event) {
        Entity entity = event.getEntity();

        if (entity.level().isClientSide) {
            return;
        }

        if (entity.getType() != EntityType.ITEM) {
            return;
        }

        ItemEntity itemEntity = (ItemEntity) entity;

        if (!itemEntity.getItem().is(Items.SPECTRAL_ARROW)) {
            return;
        }

        int i = itemEntity.getItem().getCount() * 3 / 4;
        int count = (int) (i + Math.min(((itemEntity.getItem().getCount() - i) * random.nextFloat(0, 1)), i));

        ItemEntity result = new ItemEntity(itemEntity.level(), itemEntity.getX(), itemEntity.getY(), itemEntity.getZ(), new ItemStack(ModItems.PHANTASM_ARROW_ITEM.get(), count));
        result.setDeltaMovement(0, 0.5, 0);
        result.setInvulnerable(true);
        itemEntity.level().addFreshEntity(result);
        itemEntity.discard();
    }
}
